package br.ufpe.cin.camid.core.lifecycle;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import br.ufpe.cin.camid.core.objects.ManagedObjectHandler;

import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;

public class ObjectRegistry {
	
	private Map<String, ManagedObjectHandler> objectIdentityMap;
	
	private Multimap<Class<?>, ManagedObjectHandler> objectDefinitionMap;
	
	public ObjectRegistry()
	{
		objectIdentityMap = new HashMap<String, ManagedObjectHandler> ();
		objectDefinitionMap = HashMultimap.create();
	}
	
	public boolean add(ManagedObjectHandler handler)
	{
		if(!contains(handler.getId()))
		{
			objectIdentityMap.put(handler.getId(), handler);
			objectDefinitionMap.put(handler.getObject().getClass(), handler);
			return true;
		}
		
		return false;
	}

	public boolean contains(String id) 
	{	
		boolean result = objectIdentityMap.containsKey(id);
		return result;
	}

	public Collection<ManagedObjectHandler> findByDefinition(
			Class<?> definition) {
		
		Collection<ManagedObjectHandler> handlers = objectDefinitionMap.get(definition);
		return handlers;
	}

	public ManagedObjectHandler remove(String id) 
	{	
		ManagedObjectHandler handler = objectIdentityMap.remove(id);
		if(handler != null)
			objectDefinitionMap.remove(handler.getObject().getClass(), handler);
		return handler;
	}

	public ManagedObjectHandler find(String id) 
	{
		ManagedObjectHandler handler = objectIdentityMap.get(id);
		return handler;
	}
	
	
}
